<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="pileSn">
        <el-input
          v-model="queryParams.pileSn"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="deployStatus">
        <el-select v-model="queryParams.deployStatus" placeholder="请选择设备状态" clearable style="width: 150px">
          <el-option
            v-for="dict in pile_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:pile:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:pile:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:pile:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:pile:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编号" align="center" prop="pileSn" />
      <el-table-column label="设备名称" align="center" prop="pileName" />
      <el-table-column label="设备型号" align="center" >
        <template #default="scope">
          <div v-for="item in pileModelList" :key="item.id">
            <span v-if="item.id == scope.row.modelId">{{item.modelName}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="合作商" align="center" >
        <template #default="scope">
          <div v-for="item in partnerList" :key="item.id">
            <span v-if="item.id == scope.row.partnerId">{{item.partnerName}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="left" prop="addr" show-overflow-tooltip />
      <el-table-column label="设备状态" align="center" prop="deployStatus">
        <template #default="scope">
          <dict-tag :options="pile_status" :value="scope.row.deployStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdatePlan(scope.row)" v-hasPermi="['manage:plan:list']">套餐</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdatePolicy(scope.row)" v-hasPermi="['manage:policy:list']">策略</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:pile:edit']">修改</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:pile:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电桩设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="pileRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="pileSn">
          <span>{{ form.pileSn == null ? '系统自动生成':form.pileSn }}</span>
        </el-form-item>
        <el-form-item v-if="form.id != null " label="创建时间" prop="createTime">
          <span>{{ parseTime(form.createTime,"{y}-{m}-{d}") }}</span>
        </el-form-item>
        <el-form-item label="设备名称" prop="pileName">
          <el-input v-model="form.pileName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择设备型号" clearable style="width: 100%">
            <el-option
              v-for="item in pileModelList"
              :key="item.id"
              :label="item.modelName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备点位" prop="nodeId">
          <el-select v-model="form.nodeId" placeholder="请选择点位" clearable style="width: 100%">
            <el-option
              v-for="item in nodeList"
              :key="item.id"
              :label="item.nodeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.id != null" label="合作商" prop="nodeId">
            <div v-for="item in partnerList" :key="item.id">
              <span v-if="item.id == form.partnerId">{{item.partnerName}}</span>
            </div>
        </el-form-item>
        <el-form-item v-if="form.id != null" label="所属区域" prop="regionId">
          <div v-for="item in regionList" :key="item.id">
            <span v-if="item.id == form.regionId">{{item.regionName}}</span>
          </div>
        </el-form-item>
        <el-form-item v-if="form.id != null" label="设备地址" prop="regionId">
            <span >{{form.addr}}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备策略分配对话框 -->
    <el-dialog 
      title="设备策略分配" 
      v-model="pileOpen" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
    >
      <div v-loading="policyLoading">
      <!-- 设备基本信息 -->
      <el-form ref="mainForm" :model="formData" label-width="100px">
        <el-form-item label="设备编号" prop="pileSn">
          <el-input v-model="formData.pileSn" placeholder="设备编号" disabled />
        </el-form-item>
      </el-form>

      <!-- 策略分配列表 -->
      <div class="strategy-section">
        <div class="section-header">
          <h3>策略列表</h3>
          <el-button
            type="primary" 
            size="small" 
            @click="handleAddStrategy"
          >
            添加策略
          </el-button>
        </div>
        
        <template v-if="formData.policyList.length > 0">
          <el-form 
            ref="strategiesForm" 
            :model="formData"
          >
             <div 
               v-for="(strategy, index) in formData.policyList.filter(s => s != null)"
               :key="strategy.policyId || index"
               class="strategy-item"
             >
              <el-card shadow="hover" class="strategy-card">
                <el-row :gutter="20">
                  <el-col :span="18">
                    <el-form-item
                      label="策略名称"
                    >
                      <el-select 
                        v-model="strategy.policyId" 
                        placeholder="请选择策略"
                        clearable
                        filterable
                        style="width: 100%"
                      >
                        <el-option
                          v-for="policy in policyList"
                          :key="policy.policyId"
                          :label="policy.policyName"
                          :value="policy.policyId"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  
                  <el-col :span="6">
                    <div class="strategy-actions">
                      <el-button 
                        size="small" 
                        type="danger" 
                        @click="() => handleDeleteStrategy(index)"
                      >
                        删除
                      </el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-card>
              
              <el-divider v-if="index < formData.policyList.filter(s => s != null).length - 1" />
            </div>
          </el-form>
        </template>
        
        <!-- 无策略提示 -->
        <template v-else>
          <div class="empty-tip">
            <el-empty description="暂无策略，可以为设备不分配策略或添加策略" :image-size="80" />
          </div>
        </template>
      </div>
      
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPolicy">取 消</el-button>
          <el-button type="primary" @click="submitPolicy">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备套餐分配对话框 -->
    <el-dialog 
      title="设备套餐分配" 
      v-model="planOpen" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
    >
      <div v-loading="planLoading">
      <!-- 设备基本信息 -->
      <el-form ref="planMainForm" :model="planFormData" label-width="100px">
        <el-form-item label="设备编号" prop="pileSn">
          <el-input v-model="planFormData.pileSn" placeholder="设备编号" disabled />
        </el-form-item>
      </el-form>

      <!-- 套餐分配列表 -->
      <div class="plan-section">
        <div class="section-header">
          <h3>套餐列表</h3>
          <el-button
            type="primary" 
            size="small" 
            @click="handleAddPlan"
          >
            添加套餐
          </el-button>
        </div>
        
        <template v-if="planFormData.plansList.length > 0">
          <el-form 
            ref="plansForm" 
            :model="planFormData"
          >
             <div 
               v-for="(plan, index) in planFormData.plansList.filter(p => p != null)"
               :key="plan.id || index"
               class="plan-item"
             >
              <el-card shadow="hover" class="plan-card">
                <el-row :gutter="20">
                  <el-col :span="18">
                    <el-form-item
                      label="套餐名称"
                    >
                      <el-select 
                        v-model="plan.id" 
                        placeholder="请选择套餐"
                        clearable
                        filterable
                        style="width: 100%"
                      >
                        <el-option
                          v-for="planItem in planList"
                          :key="planItem.id"
                          :label="planItem.planName"
                          :value="planItem.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  
                  <el-col :span="6">
                    <div class="plan-actions">
                      <el-button 
                        size="small" 
                        type="danger" 
                        @click="() => handleDeletePlan(index)"
                      >
                        删除
                      </el-button>
                    </div>
                  </el-col>
                </el-row>
              </el-card>
              
              <el-divider v-if="index < planFormData.plansList.filter(p => p != null).length - 1" />
            </div>
          </el-form>
        </template>
        
        <!-- 无套餐提示 -->
        <template v-else>
          <div class="empty-tip">
            <el-empty description="暂无套餐，可以为设备不分配套餐或添加套餐" :image-size="80" />
          </div>
        </template>
      </div>
      
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPlan">取 消</el-button>
          <el-button type="primary" @click="submitPlan">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.strategy-section {
  margin-top: 20px;
}

.plan-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #303133;
}

.strategy-item {
  margin-bottom: 15px;
}

.plan-item {
  margin-bottom: 15px;
}

.strategy-card {
  border-radius: 8px;
}

.plan-card {
  border-radius: 8px;
}

.strategy-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.plan-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  text-align: right;
}
</style>

<script setup name="Pile">
import { getCurrentInstance, ref, reactive, toRefs, nextTick } from 'vue'
import { listPile, getPile, delPile, addPile, updatePile, listPolicyByPileId, assignPilePolicy,listPlanByPileId,assignPilePlan } from "@/api/manage/pile"
import { listPileModel } from "@/api/manage/pileModel"
import { listPartner } from "@/api/manage/partner"
import { listNode } from "@/api/manage/node"
import { listRegion } from "@/api/manage/region"
import { listPolicy } from "@/api/manage/policy"
import { listPlan } from "@/api/manage/plan"
import { loadAllParams } from "@/api/page"
import { parseTime } from "@/utils/ruoyi"

const { proxy } = getCurrentInstance()
const { pile_status } = proxy.useDict('pile_status')

// -----------------

const formData = ref({
  id: null,
  pileSn: null, 
  policyList: []
})

// 套餐分配相关数据
const planFormData = ref({
  id: null,
  pileSn: null, 
  plansList: []
})

// 当前操作的设备ID
const currentPileId = ref(null)

// 套餐分配对话框控制
const planOpen = ref(false)
const planLoading = ref(false)



// 添加策略
const handleAddStrategy = () => {
  try {
    // 确保添加的是一个有效的策略对象
    formData.value.policyList.push({ 
      policyId: null
    });
  } catch (error) {
    console.error('添加策略失败:', error);
    proxy.$message.error('添加策略失败');
  }
}

// 删除策略
const handleDeleteStrategy = (index) => {
  if (index >= 0 && index < formData.value.policyList.length) {
    formData.value.policyList.splice(index, 1);
  }
}

// 添加套餐
const handleAddPlan = () => {
  try {
    // 确保添加的是一个有效的套餐对象
    planFormData.value.plansList.push({ 
      id: null
    });
  } catch (error) {
    console.error('添加套餐失败:', error);
    proxy.$message.error('添加套餐失败');
  }
}

// 删除套餐
const handleDeletePlan = (index) => {
  if (index >= 0 && index < planFormData.value.plansList.length) {
    planFormData.value.plansList.splice(index, 1);
  }
}

// 取消策略分配
const cancelPolicy = () => {
  pileOpen.value = false;
  policyLoading.value = false;
  resetFormData();
}

// 重置表单数据
const resetFormData = () => {
  formData.value.id = null;
  formData.value.pileSn = null;
  formData.value.policyList = [];
  currentPileId.value = null;
  policyLoading.value = false;
}

const submitPolicy = () => {
  try {
    // 验证表单
    
    // 过滤掉无效的策略对象，确保所有策略都有policyId
    const validStrategies = formData.value.policyList.filter(strategy => 
      strategy && strategy.policyId !== null && strategy.policyId !== undefined && strategy.policyId !== ''
    );
    
    // 检查是否有未选择的策略（如果有策略项但未选择）
    const unselectedStrategies = formData.value.policyList.filter(strategy => 
      strategy && (strategy.policyId === null || strategy.policyId === undefined || strategy.policyId === '')
    );
    
    if (unselectedStrategies.length > 0) {
      proxy.$message.warning('请选择所有策略或删除未选择的策略项');
      return;
    }
    
    // 验证是否有重复的策略（只有当有策略时才检查）
    if (validStrategies.length > 1) {
      const policyIds = validStrategies.map(strategy => strategy.policyId);
      const uniquePolicyIds = [...new Set(policyIds)];
      if (policyIds.length !== uniquePolicyIds.length) {
        proxy.$message.warning('不能选择重复的策略');
        return;
      }
    }
    
    // 提交策略分配
    const submitData = {
      id: formData.value.id,
      pileSn: formData.value.pileSn,
      policyList: validStrategies
    };
    
    console.log('提交策略分配:', submitData);
    
    // 调用后端API提交策略分配
    assignPilePolicy(submitData).then(response => {
      console.log('策略分配成功响应:', response);
      proxy.$modal.msgSuccess("策略分配成功");
      pileOpen.value = false;
      getList();
    }).catch(error => {
      console.error('策略分配失败:', error);
      console.error('错误详情:', {
        message: error.message,
        response: error.response,
        request: error.request,
        config: error.config,
        stack: error.stack
      });
      
      // 根据不同的错误类型显示不同的错误信息
      if (error.message === 'Failed to fetch') {
        proxy.$message.error('网络请求失败，请检查后端服务是否启动');
      } else if (error.response) {
        // 服务器响应了错误状态码
        const status = error.response.status;
        const data = error.response.data;
        console.error('HTTP状态码:', status, '响应数据:', data);
        
        if (status === 400) {
          proxy.$message.error(`请求参数错误: ${data?.msg || '请检查提交的数据格式'}`);
        } else if (status === 401) {
          proxy.$message.error('未授权访问，请重新登录');
        } else if (status === 403) {
          proxy.$message.error('权限不足，无法执行此操作');
        } else if (status === 404) {
          proxy.$message.error('接口不存在，请检查API路径');
        } else if (status === 500) {
          proxy.$message.error(`服务器内部错误: ${data?.msg || '请联系管理员'}`);
        } else {
          proxy.$message.error(`请求失败 (${status}): ${data?.msg || '未知错误'}`);
        }
      } else if (error.request) {
        // 请求已发出但没有收到响应
        proxy.$message.error('请求超时或后端服务未响应');
      } else if (error.message === '操作失败') {
        // 后端返回的业务逻辑错误
        proxy.$message.error('策略分配失败，请检查数据是否正确');
        console.error('提交的数据:', submitData);
      } else {
        proxy.$message.error(`策略分配失败: ${error.message}`);
      }
    });
  } catch (error) {
    console.error('提交策略时发生错误:', error);
    proxy.$message.error('提交策略失败，请重试');
  }
};
// ----------------

const pileList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pileSn: null,
    pileName: null,
    modelId: null,
    regionId: null,
    nodeId: null,
    nodeType: null,
    partnerId: null,
    deployStatus: null,
    deviceStatus: null,
    strategyId: null,
  },
  rules: {
    modelId: [
      { required: true, message: "设备类型不能为空", trigger: "blur" }
    ],
    nodeId: [
      { required: true, message: "所属点位不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询电桩设备管理列表 */
function getList() {
  loading.value = true
  listPile(queryParams.value).then(response => {
    pileList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pileSn: null,
    pileName: null,
    modelId: null,
    regionId: null,
    nodeId: null,
    nodeType: null,
    partnerId: null,
    addr: null,
    longitude: null,
    latitude: null,
    deployStatus: null,
    deviceStatus: null,
    clientId: null,
    strategyId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("pileRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加电桩设备管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPile(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改电桩设备管理"
  })
}

/** 设备策略分配 */
const pileOpen = ref(false)
const policyLoading = ref(false)
function handleUpdatePolicy(row) {
  currentPileId.value = row.id
  formData.value.id = row.id
  formData.value.policyList = []
  formData.value.pileSn = row.pileSn
  policyLoading.value = true
  
  listPolicyByPileId(row.id).then(response => {
    console.log('获取策略响应:', response)
    if (response.data && response.data.length > 0) {
      response.data.forEach(policy => {
        formData.value.policyList.push(policy);
      });
    } else {
      console.log("无策略")
      formData.value.policyList = []
    }
    console.log('处理后的策略数据:', formData.value.policyList)
    pileOpen.value = true
  }).catch(error => {
    console.error('获取策略失败:', error)
    formData.value.policyList = []
    pileOpen.value = true
  }).finally(() => {
    policyLoading.value = false
  })
}

/** 设备套餐分配 */
function handleUpdatePlan(row) {
  currentPileId.value = row.id
  planFormData.value.id = row.id
  planFormData.value.plansList = []
  planFormData.value.pileSn = row.pileSn
  planLoading.value = true
  
  // 这里需要调用获取设备套餐的API，暂时使用空数组
  listPlanByPileId(row.id).then(response => {
    console.log('获取套餐响应:', response)
    if (response.data && response.data.length > 0) {
      response.data.forEach(plan => {
        planFormData.value.plansList.push(plan);
      });
    } else {
      console.log("无套餐")
      planFormData.value.plansList = []
    }
    console.log('处理后的套餐数据:', planFormData.value.plansList)
    planOpen.value = true
  }).catch(error => {
    console.error('获取套餐失败:', error)
    planFormData.value.plansList = []
    planOpen.value = true
  }).finally(() => {
    planLoading.value = false
  })
  
  // 临时实现，直接打开对话框
  planFormData.value.plansList = []
  planOpen.value = true
  planLoading.value = false
}

// 取消套餐分配
const cancelPlan = () => {
  planOpen.value = false;
  planLoading.value = false;
  resetPlanFormData();
}

// 重置套餐表单数据
const resetPlanFormData = () => {
  planFormData.value.id = null;
  planFormData.value.pileSn = null;
  planFormData.value.plansList = [];
  currentPileId.value = null;
  planLoading.value = false;
}

// 提交套餐分配
const submitPlan = () => {
  try {
    // 验证表单
    
    // 过滤掉无效的套餐对象，确保所有套餐都有id
    const validPlans = planFormData.value.plansList.filter(plan => 
      plan && plan.id !== null && plan.id !== undefined && plan.id !== ''
    );
    
    // 检查是否有未选择的套餐（如果有套餐项但未选择）
    const unselectedPlans = planFormData.value.plansList.filter(plan => 
      plan && (plan.id === null || plan.id === undefined || plan.id === '')
    );
    
    if (unselectedPlans.length > 0) {
      proxy.$message.warning('请选择所有套餐或删除未选择的套餐项');
      return;
    }
    
    // 验证是否有重复的套餐（只有当有套餐时才检查）
    if (validPlans.length > 1) {
      const planIds = validPlans.map(plan => plan.id);
      const uniquePlanIds = [...new Set(planIds)];
      if (planIds.length !== uniquePlanIds.length) {
        proxy.$message.warning('不能选择重复的套餐');
        return;
      }
    }
    
    // 提交套餐分配
    const submitData = {
      id: planFormData.value.id,
      pileSn: planFormData.value.pileSn,
      plansList: validPlans
    };
    
    console.log('提交套餐分配:', submitData);
    
    // 调用后端API提交套餐分配
    assignPilePlan(submitData).then(response => {
      proxy.$modal.msgSuccess("套餐分配成功");
      planOpen.value = false;
      getList();
    }).catch(error => {
      console.error('套餐分配失败:', error);
      proxy.$message.error('套餐分配失败');
    });
    
    // 临时实现，直接关闭对话框
    planOpen.value = false;
  } catch (error) {
    console.error('提交套餐时发生错误:', error);
    proxy.$message.error('提交套餐失败，请重试');
  }
};
/** 提交按钮 */
function submitForm() {
  proxy.$refs["pileRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePile(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPile(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除电桩设备管理编号为"' + _ids + '"的数据项？').then(function() {
    return delPile(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/pile/export', {
    ...queryParams.value
  }, `pile_${new Date().getTime()}.xlsx`)
}

/** 查询设备类型列表 */
const pileModelList = ref([])
function getPileModel() {
  try {
    const params = loadAllParams?.value || { pageNum: 1, pageSize: 10000 };
    listPileModel(params).then(response => {
      if (response && response.rows) {
        pileModelList.value = response.rows;
      } else {
        pileModelList.value = [];
      }
    }).catch(error => {
      console.error('获取设备类型列表失败:', error);
      pileModelList.value = [];
    });
  } catch (error) {
    console.error('获取设备类型列表时发生错误:', error);
    pileModelList.value = [];
  }
}

/** 查询合作商列表 */
const partnerList = ref([])
function getParnter() {
  try {
    const params = loadAllParams?.value || { pageNum: 1, pageSize: 10000 };
    listPartner(params).then(response => {
      if (response && response.rows) {
        partnerList.value = response.rows;
      } else {
        partnerList.value = [];
      }
    }).catch(error => {
      console.error('获取合作商列表失败:', error);
      partnerList.value = [];
    });
  } catch (error) {
    console.error('获取合作商列表时发生错误:', error);
    partnerList.value = [];
  }
}

/** 查询点位列表 */
const nodeList = ref([])
function getNode() {
  try {
    const params = loadAllParams?.value || { pageNum: 1, pageSize: 10000 };
    listNode(params).then(response => {
      if (response && response.rows) {
        nodeList.value = response.rows;
      } else {
        nodeList.value = [];
      }
    }).catch(error => {
      console.error('获取点位列表失败:', error);
      nodeList.value = [];
    });
  } catch (error) {
    console.error('获取点位列表时发生错误:', error);
    console.error('获取点位列表时发生错误:', error);
    nodeList.value = [];
  }
}

/** 查询区域列表 */ 
const regionList = ref([])
function getRegionList() {
  try {
    const params = loadAllParams?.value || { pageNum: 1, pageSize: 10000 };
    listRegion(params).then(response => {
      if (response && response.rows) {
        regionList.value = response.rows;
      } else {
        regionList.value = [];
      }
    }).catch(error => {
      console.error('获取区域列表失败:', error);
      regionList.value = [];
    });
  } catch (error) {
    console.error('获取区域列表时发生错误:', error);
    regionList.value = [];
  }
}

/** 查询策略列表 */ 
const policyList = ref([])
function getPolicyList() {
  try {
    const params = loadAllParams?.value || { pageNum: 1, pageSize: 10000 };
    listPolicy(params).then(response => {
      if (response && response.rows) {
        policyList.value = response.rows;
      } else {
        policyList.value = [];
      }
    }).catch(error => {
      console.error('获取策略列表失败:', error);
      policyList.value = [];
    });
  } catch (error) {
    console.error('获取策略列表时发生错误:', error);
    policyList.value = [];
  }
}

/** 查询套餐列表 */ 
const planList = ref([])
function getPlanList() {
  try {
    // 检查参数
    const params = loadAllParams?.value || { pageNum: 1, pageSize: 10000 };
    console.log('获取套餐列表参数:', params);
    
    listPlan(params).then(response => {
      console.log('套餐列表响应:', response);
      if (response && response.rows) {
        planList.value = response.rows;
      } else {
        planList.value = [];
        console.warn('套餐列表响应格式异常:', response);
      }
    }).catch(error => {
      console.error('获取套餐列表失败:', error);
      planList.value = [];
      // 不显示错误提示，避免影响页面正常加载
    });
  } catch (error) {
    console.error('获取套餐列表时发生错误:', error);
    planList.value = [];
  }
}


// 使用nextTick确保在DOM更新后初始化数据
nextTick(() => {
  getPolicyList()
  getPlanList()
  getRegionList()
  getNode()
  getPileModel()
  getParnter()
  getList()
})
</script>

